package com.content.scaffold.common.config;

import com.content.scaffold.common.identity.IdGenerator;
import com.content.scaffold.common.identity.SnowflakeIdGenerator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Random;

/**
 * @author xiaojl
 */
@Slf4j
@Configuration
public class AutoGeneratorIdConfig {
    private static final Random RANDOM = new Random();


    @Bean
    @ConditionalOnMissingBean(IdGenerator.class)
    public IdGenerator idGenerator() {
        long workerId = random(SnowflakeIdGenerator.maxWorkerId);
        log.warn("snowflake worker id not set, generate random worker id: {}", workerId);
        long datacenterId = random(SnowflakeIdGenerator.maxDataCenterId);
        log.warn("snowflake datacenter id not set, generate random datacenter id {}", datacenterId);
        return new SnowflakeIdGenerator(workerId, datacenterId);
    }

    private long random(long max) {
        return RANDOM.nextInt((int) max);
    }

}
